<script lang="jsx" setup>
import { nextTick, ref } from 'vue';
import { DeleteOutlined, DownloadOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import { useAuthStore } from '@/store/modules/auth';
import {
  addBoard,
  deleteBoard,
  exportBoard,
  getLocationList,
  receiveBoard,
  returnBoard,
  scrapBoard,
  updateBoard
} from '@/service/api/modules/workwear/board-management';
import Add from './modules/add.vue';
import List from './modules/record-list.vue';

const authStore = useAuthStore();
const useModal = window.$useModal;
const commonSearchRef = ref(null);
const searchParams = ref({
  state: null,
  moduleNo: null,
  frameNo: null,
  screenTypeName: null
});

const stateList = [
  {
    label: '入库',
    value: '0'
  },
  {
    label: '领取',
    value: '1'
  },
  {
    label: '使用',
    value: '2'
  }
];

const searchFormList = [
  {
    type: 'select',
    key: 'state',
    label: '状态',
    placeholder: '请选择状态',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4,
    selectOptions: stateList
  },
  {
    type: 'input',
    key: 'moduleNo',
    label: '生产型号',
    placeholder: '请输入生产型号',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4
  },
  {
    type: 'input',
    key: 'frameNo',
    label: '网框编码',
    placeholder: '请输入网框编码',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4
  },
  {
    type: 'input',
    key: 'screenTypeName',
    label: '网板类型',
    placeholder: '请输入网板类型',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 4
  }
];

const tableRef = ref(null);

const currentRecordRow = ref(null);

const { handleShow: handleShowList } = useModal({
  modalOption: {
    width: '1250px',
    height: '70vh',
    title: '记录',
    destroyOnClose: true,
    cancelBtnText: '关闭',
    showConfirmBtn: false
  },
  component: () => <List row-data={currentRecordRow.value}></List>
});

function handleList(row) {
  currentRecordRow.value = row;
  handleShowList();
}

const column = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    fixed: 'left',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'screenNo',
    dataIndex: 'screenNo',
    title: '网板编码',
    align: 'center',
    checked: true,
    fixed: 'left',
    ellipsis: true,
    width: 160
    // customRender: ({ record }) => {
    //   return (
    //     <Button type="link" onClick={() => handleList(record)}>
    //       {record.screenNo}
    //     </Button>
    //   );
    // }
  },
  {
    key: 'frameNo',
    dataIndex: 'frameNo',
    title: '网框编码',
    align: 'center',
    checked: true,
    ellipsis: true,
    fixed: 'left',
    width: 100
  },
  {
    key: 'moduleNo',
    dataIndex: 'moduleNo',
    title: '生产型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    fixed: 'left',
    width: 150
  },

  {
    key: 'remark',
    dataIndex: 'remark',
    title: '备注',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  },

  {
    key: 'state',
    dataIndex: 'state',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 70,
    customRender: ({ record }) => {
      return stateList[Number(record.state)]?.label || '';
    }
  },
  {
    key: 'pntType',
    dataIndex: 'pntType',
    title: '型号类型',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },
  {
    key: 'screenTypeName',
    dataIndex: 'screenTypeName',
    title: '网板类型',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'face',
    dataIndex: 'face',
    title: '面向',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },

  {
    key: 'dateCode',
    dataIndex: 'dateCode',
    title: '周期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },
  {
    key: 'meshCount',
    dataIndex: 'meshCount',
    title: '网纱T数',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },
  {
    key: 'locationName',
    dataIndex: 'locationName',
    title: '存放区域',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },

  {
    key: 'techName',
    dataIndex: 'techName',
    title: '使用工艺',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'totalLive',
    dataIndex: 'totalLive',
    title: '使用寿命',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },
  {
    key: 'useCount',
    dataIndex: 'useCount',
    title: '印次',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },
  // {
  //   key: 'washCount',
  //   dataIndex: 'washCount',
  //   title: '翻洗次数',
  //   align: 'center',
  //   checked: true,
  //   ellipsis: true,
  //   width: 100
  // },
  {
    key: 'tensionA',
    dataIndex: 'tensionA',
    title: 'A点张力',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },
  {
    key: 'tensionB',
    dataIndex: 'tensionB',
    title: 'B点张力',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },
  {
    key: 'tensionC',
    dataIndex: 'tensionC',
    title: 'C点张力',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },
  {
    key: 'tensionD',
    dataIndex: 'tensionD',
    title: 'D点张力',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },
  {
    key: 'tensionE',
    dataIndex: 'tensionE',
    title: 'E点张力',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 75
  },

  {
    key: 'totalWc',
    dataIndex: 'totalWc',
    title: '最大翻洗次数',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 110
  },
  {
    key: 'makeBy',
    dataIndex: 'makeBy',
    title: '制作人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'makeDate',
    dataIndex: 'makeDate',
    title: '制作日期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  },

  {
    key: 'recBy',
    dataIndex: 'recBy',
    title: '领取人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'recDate',
    dataIndex: 'recDate',
    title: '领取日期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  },

  {
    key: 'inBy',
    dataIndex: 'inBy',
    title: '入库人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'inDate',
    dataIndex: 'inDate',
    title: '入库日期',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  },

  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '创建人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '创建时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  },
  {
    key: 'updateBy',
    dataIndex: 'updateBy',
    title: '修改人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 100
  },
  {
    key: 'updateDate',
    dataIndex: 'updateDate',
    title: '修改时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  }
];

function search() {
  tableRef.value.getData(1);
}

function reset() {
  nextTick(() => {
    searchParams.value = {
      state: null,
      moduleNo: null,
      frameNo: null,
      screenTypeName: null
    };
    search();
  });
}

const tabaleSelect = ref([]);
function tableSelectChange(val) {
  tabaleSelect.value = val;
}

const currentRow = ref(null);
const addRef = ref(null);
const operationType = ref('add');
const { handleClose, handleLoading, handleShow, updateModalOptions } = useModal({
  modalOption: {
    width: '800px',
    height: '650px',
    destroyOnClose: true,
    title: '新增网板'
  },
  component: () => <Add ref={addRef} rowData={currentRow.value}></Add>,
  onOk: async () => {
    const data = { ...addRef.value };
    await data.validateForm();
    handleLoading(true);
    try {
      const formData = { ...data.model };
      let pro;
      if (operationType.value === 'add') {
        pro = await addBoard(formData);
      } else {
        pro = await updateBoard({ ...formData });
      }
      const { error } = await pro;
      if (!error) {
        window.$message.success('操作成功');
        handleClose();
        search();
      }
    } finally {
      handleLoading(false);
    }
  }
});
function handleAdd(row) {
  currentRow.value = row;
  console.log('row', row);

  if (row) {
    operationType.value = 'edit';
    updateModalOptions({
      title: '修改网板'
    });
  } else {
    operationType.value = 'add';
    updateModalOptions({
      title: '新增网板'
    });
  }
  handleShow();
}

// 报废
const currentScrapRow = ref(null);
const {
  handleClose: handleScrapClose,
  handleLoading: handleScrapLoading,
  handleShow: handleScrapShow
} = useModal({
  modalOption: {
    title: '报废网板',
    width: '600px',
    height: '300px',
    destroyOnClose: true
  },
  formData: {
    scrapReason: null
  },
  formList: [
    {
      type: 'dictionary',
      key: 'scrapReason',
      label: '报废原因',
      dictCode: 'board_cause_cancellation',
      selectType: 'select',
      rule: {
        required: true,
        message: '请选择报废原因',
        trigger: 'blur'
      },
      placeholder: '请选择报废原因',
      span: 24
    }
  ],
  onOk: data => {
    let list = [];

    const scrapObj = {
      scrapBy: authStore.userInfo.user.nickName || authStore.userInfo.user.userName,
      scrapDate: dayjs().format('YYYY-MM-DD HH:mm:ss')
    };
    if (currentScrapRow.value) {
      list = [{ ...currentScrapRow.value, scrapReason: data.scrapReason, ...scrapObj }];
    } else {
      list = tabaleSelect.value.map(item => ({ ...item, scrapReason: data.scrapReason, ...scrapObj }));
    }
    handleScrapLoading(true);
    scrapBoard(list)
      .then(({ error }) => {
        if (!error) {
          window.$message.success('报废成功');
          currentRecordRow.value = null;
          handleScrapClose();
          search();
        }
      })
      .finally(() => {
        handleScrapLoading(false);
      });
  },
  onCancel: () => {}
});

function handleScrap(row) {
  handleScrapShow();
  currentScrapRow.value = row;
}

// 领取
const currentRecRow = ref(null);
const {
  handleClose: handleRecClose,
  handleLoading: handleRecLoading,
  handleShow: handleRecShow
} = useModal({
  modalOption: {
    title: '网板领取',
    width: '600px',
    height: '330px',
    destroyOnClose: true
  },
  formData: {
    operator: null,
    remark: null
  },
  formList: [
    {
      type: 'dictionary',
      key: 'operator',
      label: '领取人',
      span: 24,
      placeholder: '请选择领取人',
      dictCode: 'board_rec_return',
      selectType: 'select'
    },
    {
      type: 'textarea',
      key: 'remark',
      label: '备注',
      span: 24
    }
  ],
  onOk: data => {
    let list = [];
    if (currentRecRow.value) {
      list = [{ ...currentRecRow.value, ...data }];
    } else {
      list = tabaleSelect.value.map(item => ({ ...item, ...data }));
    }
    handleRecLoading(true);
    receiveBoard(list)
      .then(({ error }) => {
        if (!error) {
          window.$message.success('领取成功');
          currentRecordRow.value = null;
          handleRecClose();
          search();
        }
      })
      .finally(() => {
        handleRecLoading(false);
      });
  }
});

function handleRec(row) {
  handleRecShow();
  currentRecRow.value = row;
}

// 获取归还网板仓位
const locationList = ref([]);
function getLocation() {
  getLocationList().then(({ data, error }) => {
    if (!error) {
      locationList.value = data.map(item => {
        return {
          value: item.locationId,
          label: item.locationName
        };
      });
    }
  });
}

getLocation();

// 归还
const currentReturnRow = ref(null);
const location = ref(null);
const {
  handleClose: handleReturnClose,
  handleLoading: handleReturnLoading,
  handleShow: handleReturnShow
} = useModal({
  modalOption: {
    title: '网板归还',
    width: '600px',
    height: '330px',
    destroyOnClose: true
  },
  formData: {
    operator: null,
    remark: null,
    location: null,
    locationId: null
  },
  formList: [
    {
      type: 'dictionary',
      key: 'operator',
      label: '归还人',
      span: 24,
      placeholder: '请选择归还人',
      dictCode: 'board_rec_return',
      selectType: 'select'
    },
    {
      type: 'select',
      key: 'locationId',
      label: '网板仓位',
      span: 24,
      placeholder: '请选择网板仓位',
      rule: {
        required: true,
        message: '请选择网板仓位',
        trigger: 'blur'
      },
      selectOptions: locationList,
      change(val) {
        console.log(val);
        location.value = locationList.value.find(item => item.value === val)?.label;
      }
    },
    {
      type: 'textarea',
      key: 'remark',
      label: '备注',
      span: 24
    }
  ],
  onOk: data => {
    let list = [];
    if (currentReturnRow.value) {
      list = [{ ...currentReturnRow.value, ...data, locationName: location.value }];
    } else {
      list = tabaleSelect.value.map(item => ({
        ...item,
        ...data,
        locationName: location.value
      }));
    }
    handleReturnLoading(true);
    returnBoard(list)
      .then(({ error }) => {
        if (!error) {
          window.$message.success('归还成功');
          currentRecordRow.value = null;
          location.value = null;
          handleReturnClose();
          search();
        }
      })
      .finally(() => {
        handleReturnLoading(false);
      });
  }
});

function handleReturn(row) {
  handleReturnShow();
  currentReturnRow.value = row;
}

// 删除
function handelDel(row) {
  let title;
  if (row) {
    title = (
      <div>
        确定<span class="color-red font-bold">删除</span>网板编号为"
        <span class="color-blue font-bold">{row.screenNo}</span>"的记录吗？
      </div>
    );
  } else {
    title = (
      <div>
        确定将所勾选的项进行<span class="color-red font-bold">删除</span>操作吗？
      </div>
    );
  }
  window.$modal.confirm({
    title,
    onOk: () => {
      let params = [];
      if (row) {
        params = [row];
      } else {
        params = tabaleSelect.value;
      }
      deleteBoard(params).then(({ error }) => {
        if (!error) {
          window.$message.success('删除成功');
          search();
        }
      });
    },
    onCancel: () => {}
  });
}

function handle(data, type) {
  console.log(data);
  switch (type) {
    case 'add':
      handleAdd();
      break;
    case 'edit':
      handleAdd(data.record);
      break;
    case 'scrap':
      handleScrap(data.record);
      break;
    case 'del':
      handelDel(data.record);
      break;
    case 'record':
      handleList(data.record);
      break;
    case 'rec':
      handleRec(data.record);
      break;
    case 'return':
      handleReturn(data.record);
      break;
    default:
  }
  data.hidePopup();
}

// 导出
function handelExport() {
  exportBoard(searchParams.value);
}

function getBg(record) {
  if (
    record.useCount !== null &&
    record.useCount !== undefined &&
    record.totalLive !== null &&
    record.totalLive !== undefined &&
    record.useCount >= Number(record.totalLive) * 0.9
  ) {
    return { backgroundColor: '#EFEF88' };
  }
  return {};
}

const tableCustomRow = record => {
  return {
    style: getBg(record)
  };
};
</script>

<template>
  <div class="board-management-page min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    ></CommonSearch>
    <Table
      ref="tableRef"
      v-model:searchParams="searchParams"
      :column="column"
      show-row-selection
      auto-generate-uuid
      row-key="screenId"
      :scroll="{ y: 'auto' }"
      is-init-get-data
      url="/qms/scrscreen/screenInfo/pageList"
      :table-custom-row="tableCustomRow"
      @table-select-change="tableSelectChange"
      @table-row-dblclick="handleList"
    >
      <template #title>
        <AButton
          v-hasAuth="['workwear:board-management:add']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          @click="handleAdd(null)"
        >
          <template #icon>
            <PlusOutlined class="align-sub" />
          </template>
          新增
        </AButton>
        <AButton
          v-hasAuth="['workwear:board-management:update']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="tabaleSelect.length != 1"
          @click="handleAdd(tabaleSelect[0])"
        >
          <template #icon>
            <EditOutlined class="align-sub" />
          </template>
          修改
        </AButton>

        <AButton
          v-hasAuth="['workwear:board-management:delete']"
          type="primary"
          danger
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="!tabaleSelect.length"
          @click="handelDel()"
        >
          <template #icon>
            <DeleteOutlined class="align-sub" />
          </template>
          批量删除
        </AButton>

        <AButton
          v-hasAuth="['workwear:board-management:scrap']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="!tabaleSelect.length"
          @click="handleScrap()"
        >
          <template #icon>
            <em class="iconfont icon-baofei align-sub"></em>
          </template>
          批量报废
        </AButton>

        <AButton
          v-hasAuth="['workwear:board-management:rec']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="!tabaleSelect.length"
          @click="handleRec()"
        >
          <template #icon>
            <em class="iconfont icon-lingqu align-sub"></em>
          </template>
          批量领取
        </AButton>

        <AButton
          v-hasAuth="['workwear:board-management:return']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          :disabled="!tabaleSelect.length"
          @click="handleReturn()"
        >
          <template #icon>
            <em class="iconfont icon-guihuan align-sub"></em>
          </template>
          批量归还
        </AButton>

        <AButton
          v-hasAuth="['workwear:board-management:download']"
          type="primary"
          class="mini-btn mr-8px"
          size="small"
          ghost
          @click="handelExport()"
        >
          <template #icon>
            <DownloadOutlined class="align-sub" />
          </template>
          导出
        </AButton>
      </template>
      <template #contextmenuPopup-orter="{ args }">
        <li v-hasAuth="['workwear:board-management:add']" class="popup-item" @click="handle(args, 'add')">
          <PlusOutlined />
          新增
        </li>
        <li v-hasAuth="['workwear:board-management:update']" class="popup-item" @click="handle(args, 'edit')">
          <EditOutlined />
          修改
        </li>
        <li v-hasAuth="['workwear:board-management:delete']" class="popup-item" @click="handle(args, 'del')">
          <DeleteOutlined />
          删除
        </li>
        <li v-hasAuth="['workwear:board-management:scrap']" class="popup-item" @click="handle(args, 'scrap')">
          <em class="iconfont icon-baofei"></em>
          报废
        </li>
        <li v-hasAuth="['workwear:board-management:rec']" class="popup-item" @click="handle(args, 'rec')">
          <em class="iconfont icon-lingqu"></em>
          领取
        </li>
        <li v-hasAuth="['workwear:board-management:return']" class="popup-item" @click="handle(args, 'return')">
          <em class="iconfont icon-guihuan"></em>
          归还
        </li>
      </template>

      <template #footer>
        <div class="flex gap-15px">
          <div class="mt5px flex line-height-14px">
            <div class="h14px w14px bg-#EFEF88"></div>
            <span>背景为网板使用寿命≥90%</span>
          </div>
        </div>
      </template>
    </Table>
  </div>
</template>

<style lang="scss" scoped>
.popup-item {
  cursor: pointer;
  padding: 8px;

  &:hover {
    background-color: var(--surely-table-row-hover-bg);
  }

  &.disabled {
    color: var(--surely-table-disabled-color);
    cursor: not-allowed;
  }
}
</style>
